<template>
  <n-drawer
    v-model:show="show"
    placement="right"
    min-w-600
    display-directive="if"
    resizable
  >
    <n-drawer-content
      :title="parentMenu ? '添加子菜单' : '添加顶级菜单'"
      closable
    >
      <n-form label-placement="left" :label-width="100">
        <n-form-item v-if="parentMenu?.id" label="父级菜单">
          <span>{{ parentMenu.name }}</span>
        </n-form-item>
        <n-form-item label="类型">
          <button-radio :options="menuTypeOptions" v-model:value="menuType" />
        </n-form-item>
      </n-form>

      <catalog-form
        v-if="menuType === CATALOG_CODE"
        ref="formRef"
        type="add"
        :parent-menu="parentMenu"
        @submit-success="onSubmitSuccess"
      />
      <page-form
        v-else-if="menuType === PAGE_CODE"
        ref="formRef"
        type="add"
        :parent-menu="parentMenu"
        @submit-success="onSubmitSuccess"
      />
      <button-form
        v-else-if="menuType === BUTTON_CODE"
        ref="formRef"
        type="add"
        :parent-menu="parentMenu"
        @submit-success="onSubmitSuccess"
      />

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="loading" @click="handleSubmit">
            提交
          </n-button>
          <n-button @click="handleReset">重置</n-button>
          <n-button @click="show = false">取消</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import { menuTypes } from "./common";
import CatalogForm from "../menu-form/catalog.vue";
import PageForm from "../menu-form/page.vue";
import ButtonForm from "../menu-form/button.vue";
import { useLoadingFunc } from "@/hooks";
import { CATALOG_CODE, PAGE_CODE, BUTTON_CODE } from "../config";

interface Props {
  /** 若存在，则添加子菜单，否则添加顶级菜单 */
  parentMenu?: Menu;
}
interface Emits {
  (e: "submitSuccess"): void;
  (e: "submitError"): void;
}
const props = defineProps<Props>();
const emits = defineEmits<Emits>();

const show = ref(false);
const menuType = ref(0);
const formRef = ref();

const menuTypeOptions = computed(() => {
  const parent = props.parentMenu;
  if (!parent || parent.type === CATALOG_CODE) {
    menuType.value = CATALOG_CODE;
    return [menuTypes.catalog, menuTypes.page];
  } else if (parent.type === PAGE_CODE) {
    menuType.value = BUTTON_CODE;
    return [menuTypes.button];
  } else return [];
});

const { loading, func: handleSubmit } = useLoadingFunc(async () => {
  await formRef.value.valid();
  await formRef.value.handleSubmit();
});

const handleReset = () => formRef.value.handleReset();

const onSubmitSuccess = () => {
  show.value = false;
  emits("submitSuccess");
};

const funShow = () => (show.value = true);
defineExpose({ show: funShow });
</script>
